package sql_models

import (
	"log"
	"time"

	"gorm.io/driver/postgres"
	"gorm.io/gorm"
)

func CreateNewLog(clientID string, connectedAt time.Time) ConnectionLog {
	return ConnectionLog{
		ClientID:           clientID,
		LastAtConnect:      connectedAt,
		SecondAtConnect:    defaultTime,
		ThirdAtConnect:     defaultTime,
		LastAtDisconnect:   defaultTime,
		SecondAtDisconnect: defaultTime,
		ThirdAtDisconnect:  defaultTime,
	}
}

func UpdateConnectionLog(log *ConnectionLog, connectedAt time.Time) {
	log.ThirdAtConnect = log.SecondAtConnect
	log.SecondAtConnect = log.LastAtConnect
	log.LastAtConnect = connectedAt
}

func UpdateDisconnectionLog(log *ConnectionLog, disconnectedAt time.Time) {
	log.ThirdAtDisconnect = log.SecondAtDisconnect
	log.SecondAtDisconnect = log.LastAtDisconnect
	log.LastAtDisconnect = disconnectedAt
}

type ConnectionLog struct {
	ID                 uint `gorm:"primaryKey"`
	ClientID           string
	LastAtConnect      time.Time
	SecondAtConnect    time.Time
	ThirdAtConnect     time.Time
	LastAtDisconnect   time.Time
	SecondAtDisconnect time.Time
	ThirdAtDisconnect  time.Time
}

type SubscribeList struct {
	ID       int `gorm:"primaryKey"`
	ClientID string
	Topic    string
	LastTime time.Time
}

var defaultTime = time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC)

var DB *gorm.DB

func PGSQL_init() {
	var err error
	// PostgreSQL 连接字符串
	dsn := "host=localhost user=honoka password=123456 dbname=mydb port=5432 sslmode=disable TimeZone=Asia/Shanghai"
	// 使用 GORM 连接 PostgreSQL
	DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatalf("连接数据库失败: %v", err)
	}
	// 自动迁移，生成数据库表
	DB.AutoMigrate(&ConnectionLog{})
	DB.AutoMigrate(&Shop{})
	DB.AutoMigrate(&IDCard{})
	DB.AutoMigrate(&Room{})
	DB.AutoMigrate(&Device{})
	shop_test()
	RegisterDevice("587619d4010722680000fc0000000000")
}
